package com.example.mobile203zlw20216061300521;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    String url="http://192.168.29.230:3000/news";
    private RecyclerView rcview;
    private List<NEWS>list=new ArrayList<>();
    Gson gson=new Gson();
    Type type=new TypeToken<List<NEWS>>(){}.getType();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        OkHttpClient okHttpClient=new OkHttpClient();
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder().url(url).build();
                Call call=okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                       String string=response.body().string();
                       list=gson.fromJson(string,type);
                        Adapter adapter=new Adapter(list);
                       runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            rcview.setAdapter(adapter);
                            rcview.setLayoutManager(linearLayoutManager);
                        }
                    });
                    }
                });
            }
        }).start();
    }

    private void initView() {
        rcview = (RecyclerView) findViewById(R.id.rcview);
    }
}